﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using EnvDTE;

namespace FindFile
{
    class SolutionSieve
    {
        internal SolutionSieve(Solution solution)
        {
            _solution = solution;
        }

        internal ICollection<PhysicalFile> SieveForPhysicalFiles()
        {
            List<PhysicalFile> physicalFiles = new List<PhysicalFile>(200);
            foreach (Project project in _solution.Projects)
            {
                if (project.ProjectItems == null)
                {
                    continue;
                }
                foreach (ProjectItem projectItem in project.ProjectItems)
                {
                    List<PhysicalFile> childPhysicalFiles = new List<PhysicalFile>();
                    this.FindAllChildPhysicalFiles(projectItem, childPhysicalFiles);
                    physicalFiles.AddRange(childPhysicalFiles);
                }
            }
            return physicalFiles;
        }

        private void FindAllChildPhysicalFiles(ProjectItem projectItem, List<PhysicalFile> childPhysicalFiles)
        {
            if (projectItem.Kind == Constants.vsProjectItemKindPhysicalFile)
            {
                PhysicalFile physicalFile = new PhysicalFile(projectItem);
                childPhysicalFiles.Add(physicalFile);
            }

            if ((projectItem.ProjectItems != null) && (projectItem.ProjectItems.Count != 0))
            {
                foreach (ProjectItem childProjectItem in projectItem.ProjectItems)
                {
                    this.FindAllChildPhysicalFiles(childProjectItem, childPhysicalFiles);
                }
            }

            // This handles "Solution Folders":
            if (projectItem.SubProject != null)
            {
                Project subProject = projectItem.SubProject;
                if (subProject.ProjectItems == null)
                {
                    return;
                }
                foreach (ProjectItem subProjectItem in subProject.ProjectItems)
                {
                    this.FindAllChildPhysicalFiles(subProjectItem, childPhysicalFiles);
                }
            }
        }

        readonly Solution _solution;
    }
}
